package com.tuling.controller;

import com.tuling.domain.User;
import com.tuling.service.UserService;
import com.tuling.service.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String str = request.getParameter("str"); // 邮箱或手机
        String pwd = request.getParameter("pwd");
        // 调用业务层
        User login = userService.login(str, pwd);
        // 根据结果响应前端
        if (login!=null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", login);
            // 重定向
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            // 转发
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}
